import React from "react";
import { useRootData } from "../../tools/useRootData";
import { Link } from "react-router-dom";
import "./index.css";

const Cart: React.FC = () => {
  const { entries, subTotal } = useRootData((store) => ({
    entries: store.cartStore.entries,
    subTotal: store.cartStore.subTotal,
  }));

  return (
    <div className="container">
      <h1 className="title">购物车</h1>
      {entries.map((entry) => (
        <div className="entry" key={entry.book.id}>
          <div className="flex-warp">
            <span className="book-name">
              书名：
              <Link to={`/detail/${entry.book.id}`}>{entry.book.name}</Link>
            </span>
            <button onClick={() => entry.remove()}>删除</button>
          </div>
          <div className="flex-warp">
            <span>单价：{entry.book.price}￥</span>
            <div>
              <span>
                共
                <input
                  className="input"
                  type="number"
                  value={entry.quantity}
                  onChange={updateEntryQuantity.bind(null, entry)}
                ></input>
                本，
              </span>
              <span>合计：{entry.price}￥</span>
            </div>
          </div>
        </div>
      ))}
      <div
        className="total"
        style={{ display: "flex", justifyContent: "flex-end" }}
      >
        总计：{subTotal}￥
      </div>
      <div style={{ display: "flex", justifyContent: "flex-end" }}>
        <button
          onClick={() =>
            window.alert(
              subTotal > 0 ? `下单成功，共计${subTotal}元` : "请添加书籍！"
            )
          }
        >
          下单
        </button>
      </div>
    </div>
  );
};

function updateEntryQuantity(entry: any, e: any) {
  if (e.target.value) entry.setQuantity(Number(e.target.value));
}
export default Cart;
